const fs = require('fs');
const path = require('path');
const logger = require('../utils/logger');

/**
 * 获取日志文件列表
 */
const getLogFiles = async (req, res, next) => {
  try {
    const logDir = process.env.LOG_FILE_PATH || './logs';
    
    // 检查日志目录是否存在
    if (!fs.existsSync(logDir)) {
      return res.json({
        code: 200,
        msg: '日志目录不存在',
        data: []
      });
    }

    // 读取日志文件列表
    const files = fs.readdirSync(logDir)
      .filter(file => file.endsWith('.log'))
      .map(file => {
        const filePath = path.join(logDir, file);
        const stats = fs.statSync(filePath);
        return {
          filename: file,
          size: stats.size,
          created_at: stats.birthtime,
          modified_at: stats.mtime
        };
      })
      .sort((a, b) => b.modified_at - a.modified_at); // 按修改时间降序

    res.json({
      code: 200,
      msg: '获取成功',
      data: files
    });
  } catch (err) {
    logger.error('获取日志文件列表失败', { error: err.message });
    next(err);
  }
};

/**
 * 读取日志文件内容
 */
const getLogContent = async (req, res, next) => {
  try {
    const { filename } = req.params;
    const { page = 1, pageSize = 100, level, search } = req.query;
    
    const logDir = process.env.LOG_FILE_PATH || './logs';
    const filePath = path.join(logDir, filename);

    // 安全检查：防止路径遍历攻击
    if (!filename.endsWith('.log') || filename.includes('..') || filename.includes('/')) {
      return res.status(400).json({
        code: 400,
        msg: '非法的文件名'
      });
    }

    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        code: 404,
        msg: '日志文件不存在'
      });
    }

    // 读取文件内容
    const content = fs.readFileSync(filePath, 'utf8');
    let lines = content.split('\n').filter(line => line.trim());

    // 解析日志行
    const parsedLogs = lines.map((line, index) => {
      const match = line.match(/\[(.*?)\] \[(.*?)\] (.*)/);
      if (match) {
        return {
          id: index + 1,
          timestamp: match[1],
          level: match[2],
          message: match[3],
          raw: line
        };
      }
      return {
        id: index + 1,
        timestamp: '',
        level: 'UNKNOWN',
        message: line,
        raw: line
      };
    });

    // 过滤
    let filteredLogs = parsedLogs;
    
    // 按日志级别过滤
    if (level && level !== 'ALL') {
      filteredLogs = filteredLogs.filter(log => log.level === level);
    }

    // 按关键词搜索
    if (search) {
      const searchLower = search.toLowerCase();
      filteredLogs = filteredLogs.filter(log => 
        log.message.toLowerCase().includes(searchLower) ||
        log.level.toLowerCase().includes(searchLower)
      );
    }

    // 反转数组，使最新的日志在前面
    filteredLogs = filteredLogs.reverse();

    // 分页
    const total = filteredLogs.length;
    const start = (page - 1) * pageSize;
    const end = start + parseInt(pageSize);
    const paginatedLogs = filteredLogs.slice(start, end);

    res.json({
      code: 200,
      msg: '获取成功',
      data: {
        list: paginatedLogs,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (err) {
    logger.error('读取日志文件失败', { error: err.message });
    next(err);
  }
};

/**
 * 下载日志文件
 */
const downloadLogFile = async (req, res, next) => {
  try {
    const { filename } = req.params;
    const logDir = process.env.LOG_FILE_PATH || './logs';
    const filePath = path.join(logDir, filename);

    // 安全检查
    if (!filename.endsWith('.log') || filename.includes('..') || filename.includes('/')) {
      return res.status(400).json({
        code: 400,
        msg: '非法的文件名'
      });
    }

    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        code: 404,
        msg: '日志文件不存在'
      });
    }

    // 设置响应头
    res.setHeader('Content-Type', 'text/plain');
    res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);

    // 发送文件
    const fileStream = fs.createReadStream(filePath);
    fileStream.pipe(res);
  } catch (err) {
    logger.error('下载日志文件失败', { error: err.message });
    next(err);
  }
};

/**
 * 清理旧日志文件
 */
const cleanOldLogs = async (req, res, next) => {
  try {
    const { days = 30 } = req.body;
    const logDir = process.env.LOG_FILE_PATH || './logs';

    if (!fs.existsSync(logDir)) {
      return res.json({
        code: 200,
        msg: '日志目录不存在',
        data: { deleted: 0 }
      });
    }

    const files = fs.readdirSync(logDir);
    const now = Date.now();
    const maxAge = days * 24 * 60 * 60 * 1000;
    let deletedCount = 0;

    files.forEach(file => {
      const filePath = path.join(logDir, file);
      const stat = fs.statSync(filePath);
      
      if (now - stat.mtimeMs > maxAge) {
        fs.unlinkSync(filePath);
        deletedCount++;
        logger.info(`已删除旧日志文件: ${file}`);
      }
    });

    res.json({
      code: 200,
      msg: `成功清理 ${deletedCount} 个旧日志文件`,
      data: { deleted: deletedCount }
    });
  } catch (err) {
    logger.error('清理日志文件失败', { error: err.message });
    next(err);
  }
};

/**
 * 获取日志统计信息
 */
const getLogStats = async (req, res, next) => {
  try {
    const { filename } = req.params;
    const logDir = process.env.LOG_FILE_PATH || './logs';
    const filePath = path.join(logDir, filename);

    // 安全检查
    if (!filename.endsWith('.log') || filename.includes('..') || filename.includes('/')) {
      return res.status(400).json({
        code: 400,
        msg: '非法的文件名'
      });
    }

    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        code: 404,
        msg: '日志文件不存在'
      });
    }

    // 读取文件内容
    const content = fs.readFileSync(filePath, 'utf8');
    const lines = content.split('\n').filter(line => line.trim());

    // 统计各级别日志数量
    const stats = {
      total: lines.length,
      ERROR: 0,
      WARN: 0,
      INFO: 0,
      DEBUG: 0,
      UNKNOWN: 0
    };

    lines.forEach(line => {
      if (line.includes('[ERROR]')) stats.ERROR++;
      else if (line.includes('[WARN]')) stats.WARN++;
      else if (line.includes('[INFO]')) stats.INFO++;
      else if (line.includes('[DEBUG]')) stats.DEBUG++;
      else stats.UNKNOWN++;
    });

    res.json({
      code: 200,
      msg: '获取成功',
      data: stats
    });
  } catch (err) {
    logger.error('获取日志统计失败', { error: err.message });
    next(err);
  }
};

module.exports = {
  getLogFiles,
  getLogContent,
  downloadLogFile,
  cleanOldLogs,
  getLogStats
};

